<?php

class Ext_Publish_Attachment_Delete
{
    protected $_userId;
    protected $_articleId;
    
    protected $_messager;
    const ARTICLE_RECORD_NOT_FOUND   = 'articleRecordNotFound';
    protected $_messageTemplates = array(
        self::ARTICLE_RECORD_NOT_FOUND   => "Article record not found.",
    );
    
    public function __construct($articleId)
    {
        $userId = Ext_Auth_Front::getInstance()->getIdentity();
        
        $this->_userId     = $userId;
        $this->_articleId  = $articleId;
        
        $this->_messager = new Ext_Messager($this->_messageTemplates);
    }
    
    public function delete($attachmentType, $attachmentDataId)
    {
        $_result = array(
            'code'      => Ext_Publish_Attachment_Delete_Result::FAILURE,
            'messages'  => array(),
        );
        
        $_articleRow = App_Model_DbTable_Article::getInstance()->getRowById($this->_articleId);
        if(!$_articleRow){
            $_result['messages'][] = $this->_messager->addMessage(self::ARTICLE_RECORD_NOT_FOUND);
            return new Ext_Publish_Attachment_Delete_Result($_result['code'], $_result['messages']);
        }
        
        $classname = "Ext_Publish_Attachment_Delete_Adapter_".ucfirst($attachmentType);
        if(!class_exists( $classname )){
            throw new Ext_Publish_Attachment_Delete_Exception("Attachment delete adapter '$attachmentType' not found.");
        }
        $_adapter = new $classname($this->_articleId, $attachmentDataId);
        $_resulter = $_adapter->delete();
        if(!$_resulter->isValid())
        {
            $_result['messages'] = $_resulter->getMessages();
            return new Ext_Publish_Attachment_Delete_Result($_result['code'], $_result['messages']);
        }
        
        $_result['code']  = Ext_Publish_Attachment_Delete_Result::SUCCESS;
        return new Ext_Publish_Attachment_Delete_Result($_result['code'], $_result['messages']);
        
    }
}
